<template>
  <div class="index-container pb-16 bg-gray-2600">
    <GoogleAuthLogin></GoogleAuthLogin>
    <banner-top :aiNum="tool_count"
      :categoriesNum="category_count"></banner-top>
    <div class="index-content">
      <div class="max-w-11xl px-4 pt-5 pb-9 mx-auto">
        <index-menu-list></index-menu-list>
        <el-divider class="my-5"></el-divider>
        <index-categories-list :categories="category_group_list"></index-categories-list>

        <div class="mt-5 space-y-10">
          <div class="md:flex md:gap-5 items-start">
            <div class="md:flex-1">
              <tools-section titleLabel="index_justLaunched"
                id="index_now-0"
                path="/new"
                :isIndex="true"
                :toolsList="new_list"
                :isFirstScreen="true">
                <div class="flex justify-center mt-8"
                  slot="ctrl">
                  <common-link path="/new"
                    class="inline-flex items-center justify-between h-12 px-6 border border-gray-1200 duration-100 hover:border-purple-1300 rounded-md group whitespace-nowrap">
                    <span class="text-base text-gray-1000 group-hover:text-purple-1300">
                      {{$t('index_discoverMoreNew')}}
                    </span>
                  </common-link>
                </div>
              </tools-section>
              <template v-if="!isLoadError">
                <tools-section :titleLabel="`${item.name}`"
                  :year="`${item.year!==fullYear && !item.is_year ? `${item.year}` : ''}`"
                  :isNoI18n="item.is_year ? true : false"
                  path="/month/:handle"
                  :isIndex="true"
                  :params="{handle: item.handle}"
                  v-for="(item, key) in date_list"
                  :key="key"
                  :loading="loading"
                  :toolsList="item.data"
                  :id="item.is_year ? `year-${item.name}-${key+1}` : `${item.name}-${key+1}`"
                  :lazyLoad="key>=1">
                  <div class="flex justify-center mt-8"
                    slot="ctrl">
                    <common-link path="/month/:handle"
                      :params="{handle: item.handle}"
                      class="inline-flex items-center justify-between h-12 px-6 border border-gray-1200 duration-100 hover:border-purple-1300 rounded-md group whitespace-nowrap">
                      <span class="text-base text-gray-1000 group-hover:text-purple-1300">
                        {{$t('index_discoverMore',{num:item.count})}}
                      </span>
                    </common-link>
                  </div>
                </tools-section>
              </template>
            </div>
            <div class="hidden md:block md:flex-shrink-0 w-sidebar"
              v-if="recommendToolsList && recommendToolsList.length > 0">
              <h3 class="text-34 text-gray-34 font-semibold">{{$t('category_featured')}}</h3>
              <div class="tools space-y-4 mt-7 px-3.5 py-4 bg-white rounded-lg">
                <min-tool-featured v-for="(item, key) in recommendToolsList"
                  :key="item.handle+'-'+key"
                  :toolPosIndex="key"
                  :toolsData="item"></min-tool-featured>
              </div>
            </div>
          </div>
        </div>
      </div>

      <letters-scroll :dateList="date_list"></letters-scroll>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'IndexPage',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error }) {
    try {
      let [searchRes] = await Promise.all([
        $axiosApi.searchLisV1(),
        /* $axiosApi.getTools({
          page: 1,
          per_page: 100,
          history_has_recommended: 1,
        }), */
      ])
      let recommendToolsList = []
      let res = {}
      if (searchRes.code === 200) {
        res.new_list = searchRes.data.new_list
        res.category_group_list = searchRes.data.category_group_list
        searchRes.data.date_list.forEach((item) => {
          const month = app.i18n.t(`${item.name}`, 'en')
          item.name = item.is_year ? item.name : `${item.name}_character`
          let dateArr = item.start_time.split('-')
          item.handle = item.is_year ? month : `${month}-${dateArr[0]}`
          item.year = parseInt(dateArr[0])
        })
        res.date_list = searchRes.data.date_list

        res.tool_count = searchRes.data.tool_count
        res.category_count = searchRes.data.category_count

        recommendToolsList =
          searchRes.data.featured_list &&
          searchRes.data.featured_list.length > 0
            ? searchRes.data.featured_list
            : []
      } else {
        if (searchRes && searchRes.code && searchRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(searchRes && searchRes.code && searchRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: searchRes.code,
          })
        }
      }

      /* if (toolsRes.code === 200) {
        recommendToolsList =
          toolsRes.data.data && toolsRes.data.data.length > 0
            ? toolsRes.data.data
            : []
      } */

      let description = app.i18n.t('indexSEODescription')
      let title = app.i18n.t('indexSEOTitle')

      //就近取整百、整千
      if (res.tool_count && res.tool_count > 100) {
        let numStr = String(parseInt(res.tool_count))
        const len = numStr.length
        const arr = numStr.split('')
        for (let i = 0; i < len; i++) {
          arr[i] = i < len - 2 ? arr[i] : '0'
        }
        let totolTools = `${arr.join('')}+`

        if (description.indexOf('1200+') >= 0) {
          description = description.replace('1200+', totolTools)
        } else {
          description = description.replace('1200', arr.join(''))
        }
      }

      return {
        ...res,
        title,
        description,
        recommendToolsList,
      }
    } catch (err) {
      console.log(err)
    }
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      new_list: [],
      month_tools_list: [],
      date_list: [],
      category_group_list: [],

      tool_count: 0,
      category_count: 0,
      loading: true,
      isLoadError: false,

      recommendToolsList: [],
      fullYear: parseInt(new Date().getFullYear()),
    }
  },
  computed: {
    ...mapState({
      countries: (state) => state.countries,
      locale: (state) => state.locale,
    }),
  },
  created() {
    //this.getMonthToolsList()
  },
  mounted() {
    this.loading = false
  },
  methods: {
    ...mapMutations(['SET_RetrackExposure']),
    async getMonthToolsList() {
      this.loading = true
      try {
        const res = await this.$axiosApi.getMonthList()
        if (res && res.code === 200) {
          this.loading = false
          this.month_tools_list = res.data.month_tools_list

          this.SET_RetrackExposure(Date.now())
        } else {
          this.getMonthToolsList()
        }
      } catch (error) {
        this.loading = false
        this.loadError()
      }
    },
    //月份数据加载失败
    loadError() {
      this.isLoadError = true
      this.date_list = []
    },
  },
}
</script>


